package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Visitors> queryVisitors(Long userId,Integer num) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.limit(num);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitors.class);
    }

    @Override
    public List<Visitors> queryVisitors(Long userId, Integer num, long time) {
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gt(time));// 9:16
        query.limit(num);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitors.class);
    }


    @Override
        public void saveVisitors(Long userId, Long visitorId){
            Visitors visitors = new Visitors();
            visitors.setId(new ObjectId());
            visitors.setVisitorUserId(visitorId);
            visitors.setUserId(userId);
            visitors.setFrom("首页");
            visitors.setDate(new Date().getTime());
            mongoTemplate.save(visitors);
    }
}
